package teach.test;

//我想学习怎么使用pull request,借你的代码练一下手  :)
public class MyList {

	public static class Node{
		Object data;
		Node next;
		public Node(Object data){
			super();
			this.data = data;
			next = null;
		}

	}
	Node head;

	public MyList(){
		head = null;
	}
	//清空链表
	public void clear(){
		head = null;
	}
	//遍历打印链表
	public void travel(){
		Node p = head;
		while(p != null){
			System.out.println(p.data);
			p = p.next; 
		}
	}
	
	//判断链表是否为null
	public boolean isEmpty(){
		
		return head == null;
	}
	
	public int size(){
		Node p = head;
		int sum = 0;
		while(p != null){
			sum ++;
			p = p.next;
		}
		return sum;
	}
	
	public void insert(Object obj, int pos){
		if(pos < 0 || pos > size()){
			throw new RuntimeException("插入的"+ pos +"越界了!");
		}
		Node newNode = new Node(obj);
		if(pos == 0){
			 newNode.next = head;
			 head = newNode;	
		}
		if(pos >= size()-1){
			get(size()-1).next = newNode;
		}else{
			newNode.next = get(pos);
			get(pos - 1).next = newNode;
		}
	}
	
	
	/**
	 * 获得特定位置的节点
	 * @param post
	 * @return
	 */
	public Node get(Integer pos){
		if(pos < 0 || pos > size()){
			throw new RuntimeException("传入的"+ pos +"越界了!");
		}
		//获取头部节点
		if(pos == 0){
			return head;
		}
		Node p = head;
		for(int i = 0; i < pos; i++){
			p = p.next;
		}
		return p;
	}


}
